import React from 'react';
import ReactDOM from 'react-dom';
import * as d3 from "d3";
import { useRef, useEffect } from "react";
import { makeStyles } from "@material-ui/core/styles";
import './DrawAllPhase.css';
import MainFootballField_bg from '../MainFootballField/assets/足球场线稿.svg';

import * as basicGraph from "../DrawGraph/DrawGraph";



const useStyle = makeStyles((theme) => ({
  svgContainer: {
    width: "90%",
    height: "80%",
    position: "relative",
  },
}));

function DrawAllPhase2 (props) {
    
    
	  const classes = useStyle();
  	const topSvg = useRef(null);
    
    

    useEffect(() =>{
      //将json文件中的数据放到一个数组中
      //测试传值是否成功
      //const a=props.data[0].length;
      //const b= 19;
      //if (a==b){alert('a')};
      
      
      const drawPos = [];
      //const drawLen = props.data[0].length;      //这个phases下有几个phase
      const matchPhases = props.data[props.index].phases;  //num指定是第几个聚类

      matchPhases.forEach((phase) =>{            //for循环遍历这个phases里的所有phase
          const eventList = phase.eventList;     //取出一个phase中的eventSequence,适用clustered data
          const eventPos = [];
          const eventLen = phase.phaseLength;    //记录这个phase下有几个event

          eventList.forEach((event) => {         //for循环遍历这个phase eventList中的所有event
              eventPos.push({                    //将event的位置信息，eventName，teamId存储   注意位置信息只需要取positions中的第一个即可
                x: event.positions[0].x,
                y: event.positions[0].y,
                eventName: event.eventName,
                teamId: event.teamId,
              });
          });

              if (eventList[eventLen - 1]?.positions[1]?.x !== 0)//如果是该phase下的最后一个event,需要补充postions中的第二个位置
              eventPos.push({
                x: eventList[eventLen - 1].positions[1].x,
                y: eventList[eventLen - 1].positions[1].y,
                eventName: eventList[eventLen - 1].eventName,
                teamId: eventList[eventLen-1].teamId,
              });
          

          drawPos.push(eventPos);  
      });


      if (topSvg.current){
          const margin = 9.5;        //边距，到时候以自己的图为准
          const svgWidth = 1050;     //绘制部分的宽度
          const svgHeight = 688;     //绘制部分的高度
          const svg = d3.select(topSvg.current);
          svg.selectAll("*").remove();  //把之前的绘制内容删除
          const myXScale = d3           //X方向线性比例尺
            .scaleLinear()
            .domain([0, 100])
            .range([0, svgWidth - 2 * margin]);
          const myYScale = d3           //Y方向线性比例尺
            .scaleLinear()
            .domain([0, 100])
            .range([0, svgHeight - 2 * margin]);
        
          //图例绘制部分！！！！！！！！！！！！到时候替换成自己的图片
          const symbolSize = 250;   //图例大小
       

        const phaseGs = svg.append("g");                //留着！！！是下方函数的变量声明

      // highlight a phase when click on the first node     高亮其中某个phase  可暂时不管
      const strokOpacity = props.ifShowAllPath ? 1 : 0;
      const highLightPhase = (phaseGroup) => {

        // highLight or turnoff node
        const currentDis = phaseGroup.selectAll("path").attr("display");
        const newDis = currentDis === "none" ? "initial" : "none";
        phaseGroup.selectAll("path").attr("display", newDis);
        //phaseGroup.selectAll("line").style('stroke-Width',5).style('stroke','white');
        // opacity
        if (!strokOpacity) {
          const currentOpac = phaseGroup
            .selectAll("line")
            .attr("stroke-opacity");
          const newOpac = currentOpac.toString() === "0" ? "1.0" : "0";
          phaseGroup.selectAll("line").attr("stroke-opacity", newOpac);
        }
      };
      const test1 = (phaseGroup) => {
        phaseGroup.selectAll("path").style("stroke-Width",4);
        phaseGroup.selectAll("line").style("stroke-Width",6);
        phaseGroup.selectAll("circle").style("stroke-Width",6);
      };
      const test2 = (phaseGroup) => {
        phaseGroup.selectAll("path").style("stroke-Width",1);
        phaseGroup.selectAll("line").style("stroke-Width",3);
        phaseGroup.selectAll("circle").style("stroke-Width",2);
      };
      //---------------------------------------------------------------------------------------------
      drawPos.forEach((phasePos, index) => {    //这里phasePos是一个包含某个phase所有位置信息，phasePos[i]指其中第i个event
        // add each phase in a group
        const phaseGroup = phaseGs.append("g").classed(`phase-${index}`, true);
        for (let i = 0; i < phasePos.length; i++) {
          let nodeColor = "#000";
          let nodeShow = "none";
          let howMargin = !phasePos[i].y
            ? -margin
            : phasePos[i].y === 100
            ? margin
            : 0;
          const translateP = `translate(${myXScale(phasePos[i].x)},${
            svgHeight + howMargin - myYScale(phasePos[i].y)
          })`;
          // if this a start node
          if (i === 0) {
            nodeColor = "#f00";
            nodeShow = "initial";
            phaseGroup
              .append("circle")
              .attr("cx", myXScale(phasePos[i].x))
              .attr("cy", svgHeight + howMargin - myYScale(phasePos[i].y))
              .attr("r", margin)
              .attr("display", nodeShow)
              .style("fill", props.circleColor)
              .style("stroke-Width",2)
              .style("stroke",props.circleStroke)
              .on("mouseover", () => {test1(phaseGroup);})
              .on("mouseout", () => {test2(phaseGroup);})
              .on("click", () => {
                highLightPhase(phaseGroup);
              });
          } else {
            switch (phasePos[i].eventName) {
              case "Pass":
                basicGraph
                  .triangle(phaseGroup, symbolSize)
                  .attr("transform", translateP)
                  .attr("fill", "#515EFF")
                  .attr("display", nodeShow)
                  .style("stroke-Width",1)
                  .style("stroke",'white');
                break;
              case "Duel":
                basicGraph
                  .wye(phaseGroup, symbolSize)
                  .attr("transform", translateP)
                  .attr("display", nodeShow)
                  .attr("fill", "#BC55F7")
                  .style("stroke-Width",1)
                  .style("stroke",'white');
                break;
              case "Shot":
                basicGraph
                  .star(phaseGroup, symbolSize)
                  .attr("transform", translateP)
                  .attr("display", nodeShow)
                  .attr("fill", "#f1404b")
                  .style("stroke-Width",1)
                  .style("stroke",'white');
                break;
              case "Free Kick":
                basicGraph
                  .square(phaseGroup, symbolSize)
                  .attr("transform", translateP)
                  .attr("display", nodeShow)
                  .attr("fill", "#FFFFF3")
                  .style("stroke-Width",1)
                  .style("stroke",'white');
                break;
              case "Others on the ball":
                basicGraph
                  .cross(phaseGroup, symbolSize)
                  .attr("transform", translateP)
                  .attr("display", nodeShow)
                  .attr("fill", "#49010F")
                  .style("stroke-Width",1)
                  .style("stroke",'white');
                break;
              default:
                basicGraph
                  .diamond(phaseGroup, symbolSize)
                  .attr("transform", translateP)
                  .attr("display", nodeShow)
                  .attr("fill", "#AACD6E")
                  .style("stroke-Width",1)
                  .style("stroke",'white');
                break;
            }
          }
          if (i < phasePos.length -1) {
            phaseGroup
              .append("line")
              .attr("x1", myXScale(phasePos[i].x))
              .attr("y1", svgHeight + howMargin - myYScale(phasePos[i].y))
              .attr("x2", myXScale(phasePos[i + 1].x))
              .attr("y2", svgHeight + howMargin - myYScale(phasePos[i + 1].y))
              .attr("stroke-opacity", strokOpacity)
              .style("stroke-width", 3)
              .style("stroke", props.lineColor)
              .style('stroke-linecap','round')
              .on("mouseover", () => {test1(phaseGroup);})
              .on("mouseout", () => {test2(phaseGroup);});
          }
        }
      });


      }
    },[props])





	return(
		<div onClick={() => {props.onClick(props);}}>
        <img src={MainFootballField_bg} style={{position:'absolute', left:'8.5px',top:'7.58px',width:'180px',height:'111.84px'}}></img>
        <svg ref={topSvg} className='svgMove1' viewBox="0 0 1050 688"></svg>
        <text style={{color:'white',position:'absolute',left:'2px',top:'2px'}}>{props.index+1}</text>
        <text style={{color:'white',position:'absolute',left:'14px',top:'6px',fontSize:'12px'}}>Shots: {props.data[props.index].shots}</text>
    </div>

		)
}


export default DrawAllPhase2;